package cn.admin.remoting.impl;

import java.net.InetSocketAddress;

public class ClientKeyUtil {

    private static final char SPLIT = '#';

    static String singleClientKey(String appName, String url) {
        return singleClientKey(appName, url, null);
    }

    static String singleClientKey(String appName, String url, InetSocketAddress localAddress) {
        return null == localAddress ? escape(appName) + SPLIT + escape(url) : escape(appName) + SPLIT + escape(url) +
                SPLIT + localAddress.getAddress().getHostAddress() + SPLIT + localAddress.getPort();
    }

    static Object[] parseClientKey(String clientKey) {
        String[] tmp = clientKey.split(String.valueOf(SPLIT));
        return new Object[]{unescape(tmp[0]), unescape(tmp[1]), tmp.length > 2 ?
                new InetSocketAddress(tmp[2], Integer.parseInt(tmp[3])) : null};
    }

    static String targetUrl(String clientKey) {
        return (String)parseClientKey(clientKey)[1];
    }

    private static String escape(String str) {
        return str.replace(SPLIT, '£');
    }

    private static String unescape(String str) {
        return str.replace('£', SPLIT);
    }

}
